package com.atguigu.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author 798133716@qq.com
 * @create 2021-02-26 18:53
 */
public class JDBCUtils {
    static String url;
    static String username;
    static String pwd;
    static String driverClass;

    static {
        InputStream is = null;
//        1读取配置文件
        try {
            Properties p = new Properties();
//        2配置文件流化
            is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
//        3加载流
            p.load(is);
//        4读取配置文件内容
            url = p.getProperty("url");
            username = p.getProperty("username");
            pwd = p.getProperty("pwd");
            driverClass = p.getProperty("driverClass");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            关资源
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static Connection getConnection(){

//            6获取连接对象
//        Driver类进行类加载

        try {
            Class.forName(driverClass);
//                获取连接对象
            Connection connection = DriverManager.getConnection(url, username, pwd);
            return connection;
        } catch (Exception e) {
            //如果出现异常就终止程序,将编译时异常转换成运行时异常
            throw new RuntimeException(e.getMessage());
        }
    }

    public static void close(PreparedStatement ps,Connection connection) {
        try {
            if (ps!=null) {
                ps.close();
            }
            if (connection!=null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(PreparedStatement ps, Connection connection, ResultSet rs) {
        close(ps,connection);
        try {
            if (rs!=null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
